package com.qdxwx.data.service.user;


import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.mapper.user.UserLetterMapper;
import com.qdxwx.data.mapper.user.UserMapper;
import com.qdxwx.data.service.order.OrderDetailService;
import com.qdxwx.data.service.system.SystemMsgService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.enums.LetterStatus;
import com.qdxwx.models.enums.LetterTemplate;
import com.qdxwx.models.enums.WebsiteProfileType;
import com.qdxwx.models.order.OrderDetail;
import com.qdxwx.models.system.SystemMsg;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserLetter;
import com.qdxwx.sms.QdxSmsClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Service
public class UserLetterServiceImpl implements UserLetterService {

    Logger logger = LoggerFactory.getLogger(UserLetterServiceImpl.class);
    @Autowired
    private UserLetterMapper userLetterMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SystemMsgService systemMsgService;
    @Autowired
    private WebsiteProfileService websiteProfileService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public int insert(UserLetter userLetter) {
        userLetter.setUpdateTime(LocalDateTime.now());
        userLetter.setCreateTime(LocalDateTime.now());
        return userLetterMapper.insertUserLetter(userLetter);
    }

    @Override
    public int delete(long id, long userId) {
        return userLetterMapper.deleteUserLetter(id, userId);
    }

    @Override
    public int delete(UserLetter userLetter) {
        return userLetterMapper.deleteUserLetterBatch(userLetter);
    }


    /**
     * 删除站内信过期消息
     */
    @Override
    public int deletePast(LocalDateTime lastTime) {
        if (lastTime != null) {
            UserLetter userLetter = new UserLetter();
            userLetter.setCreateTime(lastTime);
            return userLetterMapper.deleteUserLetterBatch(userLetter);
        }
        return 0;
    }

    @Override
    public int updateRead(UserLetter userLetter) {
        return userLetterMapper.updateIsReadBatch(userLetter);
    }

    @Override
    public int updateRead(long id) {
        return userLetterMapper.updateIsReadById(id);
    }

    @Override
    public UserLetter get(long id) {
        return userLetterMapper.selectUserLetterById(id);
    }

    @Override
    public List<UserLetter> getList(UserLetter userLetter, PageRequest page) {
        return userLetterMapper.selectUserLetterList(userLetter, page);
    }

    @Override
    public int count(UserLetter userLetter) {
        return userLetterMapper.countUserLetter(userLetter);
    }

    /**
     * 查询站内信收件箱
     */
    @Override
    public List<UserLetter> getUserInbox(User user, PageRequest page) {
        //查询用户信息
        LocalDateTime lastTime = user.getLastLoginTime();
        //查询系统发送的未读消息
        List<SystemMsg> systemMsgs = systemMsgService.getListByLastTime(lastTime);
        if (ObjectUtils.isNotNull(systemMsgs)) {
            //查出未读的系统消息插入到系统中 更新
            for (SystemMsg mgstm : systemMsgs) {
                UserLetter userLetter1 = new UserLetter();
                userLetter1.setContent(mgstm.getContent());
                userLetter1.setIsRead(LetterStatus.UNREAD.ordinal());
                userLetter1.setUserId(user.getUserId());
                userLetter1.setUserName(user.getDisplayName());
                userLetter1.setSendUserName("系统");
                userLetter1.setSendUserId(0L);
                userLetter1.setUpdateTime(LocalDateTime.now());
                userLetter1.setCreateTime(LocalDateTime.now());
                userLetterMapper.insertUserLetter(userLetter1);
            }
        }
        UserLetter query = new UserLetter();
        query.setUserId(user.getUserId());
        //查询站内信
        List<UserLetter> userLetterList = userLetterMapper.selectUserLetterList(query, page);
        //清除粉丝未读消息的缓存
        userMapper.resetLetterCount(user.getUserId());
        //上传统计系统消息时间更新最新时间
        user.setLastLoginTime(LocalDateTime.now());
        userMapper.updateLoginTime(user.getUserId(), user.getLastLoginTime());
        return userLetterList;
    }

    /**
     * 仅发送站内短信
     * @param userId 用户id
     * @param letterTemplate 短信模板（包含标题，内容，短信id）
     * @param params 短信参数
     * @return 是否成功
     */
    @Override
    public int send(long userId, LetterTemplate letterTemplate, String... params) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return 0;
        }
        if (letterTemplate == null) {
            return 0;
        }
        //获取消息下的发送方式和模板
        Map<String, Object> templateMap = websiteProfileService.getMap(WebsiteProfileType.message.toString());
        Map<String, Object> msgConfig = (Map<String, Object>) templateMap.get(letterTemplate.name());
        if (msgConfig == null) {
            logger.error("消息模板不存在：" + letterTemplate);
            return 0;
        }
        //获取消息开关配置"letter,mobile"
        String configs = msgConfig.get("sendType").toString().toLowerCase();
        int row = 0;
        //站内信
        if (configs.contains("letter")) {
            String msgContent = msgConfig.get("msgContent").toString();
            //标题暂时固定在枚举类里，后期做到配置上 msgConfig.get("msgTitle");
            String msgTitle = letterTemplate.getTitle();
            if (msgContent == null || msgContent.length() < 5) {
                logger.error("消息内容不能小于5个字符：" + msgContent);
                return 0;
            }
            //处理填充消息内容
            for (int i = 0; i < params.length; i++) {
                msgContent = msgContent.replace("{" + (i + 1) + "}", params[i]);
            }
            UserLetter userLetter = new UserLetter();
            userLetter.setTitle(msgTitle);
            userLetter.setContent(msgContent);// 添加站内信的内容
            userLetter.setUserId(user.getUserId());// 要发送的用户id
            userLetter.setUserName(user.getDisplayName());
            userLetter.setIsRead(LetterStatus.UNREAD.ordinal());// 消息未读状态
            userLetter.setSendUserId(0L);
            userLetter.setSendUserName("系统");// 会员名
            row = insert(userLetter);
        }
        /*短信发送*/
        if (configs.contains("mobile") && !TKString.isEmpty(msgConfig.get("templateId"))) {
            //为手机短信接口预留模板Id
            String templateId = msgConfig.get("templateId").toString();
            String mobile = user.getMobile();
            QdxSmsClient clientQdx = new QdxSmsClient();
            clientQdx.sendSingle(mobile, params, templateId);
            row++;
        }
        return row;
    }

    /**
     * 仅发送站内短信
     * @param userId 用户id
     * @param title 短信标题
     * @param content 短信内容
     * @return 是否成功
     */
    @Override
    public int send(long userId, String title, String content) {
        return send(userId,title ,content ,null);
    }
    /**
     * 仅发送站内短信
     * @param userId 用户id
     * @param title 短信标题
     * @param content 短信内容
     * @param sender 发信人
     * @return 是否成功
     */
    @Override
    public int send(long userId, String title, String content, User sender) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return 0;
        }
        if (content == null || content.length() < 5) {
            logger.error("消息内容不能小于5个字符：" + content);
            return 0;
        }
        UserLetter userLetter = new UserLetter();
        userLetter.setTitle(title);
        userLetter.setContent(content);// 添加站内信的内容
        userLetter.setUserId(user.getUserId());// 要发送的用户id
        userLetter.setUserName(user.getDisplayName());
        userLetter.setIsRead(LetterStatus.UNREAD.ordinal());// 消息未读状态
        userLetter.setSendUserId(sender != null ? sender.getUserId() : 0L);
        userLetter.setSendUserName(sender != null ? sender.getDisplayName() : "系统");// 会员名
        return insert(userLetter);
    }

    @Override
    public void timeOverMsg() {
        try {
            /*查询即将过去的课程信息*/
            List<OrderDetail> orderDetailList = orderDetailService.getTimeOverOrder();
            for (OrderDetail orderDetail : orderDetailList) {
                send(orderDetail.getUserId(), LetterTemplate.COURSE_OVER, orderDetail.getCourseName());
            }
        } catch (Exception e) {
            logger.error("timeOverMsg is error", e);
        }
    }

    @Override
    public int updateCombine(long userId1, long userId2) {
        if(userId1 < 1 || userId2 < 1){
            throw new RuntimeException("更新用户站内信：参数错误");
        }
        return userLetterMapper.updateCombine(userId1, userId2);
    }
}
